<template>
	<a-tree-select
		showSearch
		showArrow
		:class="['app-editor-container', 'app-orgselect', `app-input-${name}`]"
		v-model="selectTreeValue"
		:disabled="disabled || readonly"
		:treeData="treeData"
		:showCheckedStrategy="'SHOW_ALL'"
		dropdownClassName="app-orgselect__dropdown-class"
		:filterTreeNode="filterTreeNode"
		:treeCheckable="treeCheckable"
		@change="onChange"
	>
	</a-tree-select>
</template>
<script setup lang="ts">
import { Http } from '@/http';
import { orgSelectProps } from './org-select';
import { useAppStoreWithOut } from '@/store/modules/app';
import { Ref } from 'vue';
import { IEvent } from '@/core';
interface EditorEmit {
	(name: 'component-action', value: IEvent<string>): void;
}
let treeData: Ref<any[]> = ref([]);
const props = defineProps(orgSelectProps);
const selectTreeValue = ref('');
const copyFilterValue = ref('');
const { getOrgData, addOrgData } = useAppStoreWithOut();
const emit = defineEmits<EditorEmit>();
watch(
	() => props.data,
	(newVal: any, oldVal: any) => {
		if (newVal) {
			computedSelectedData();
			if (props.filter) {
				let tempFilterValue: any = initBasicData();
				if (tempFilterValue && copyFilterValue !== tempFilterValue) {
					loadTreeData(props.url.replace('${orgid}', tempFilterValue));
					copyFilterValue.value = tempFilterValue;
				}
			}
		}
	},
	{
		deep: true,
	}
);

onBeforeMount(() => {
	if (!props.filter) {
		loadTreeData(props.url);
	} else {
		computedSelectedData();
		if (props.filter) {
			let tempFilterValue: any = initBasicData();
			if (tempFilterValue && copyFilterValue !== tempFilterValue) {
				loadTreeData(props.url.replace('${orgid}', tempFilterValue));
				copyFilterValue.value = tempFilterValue;
			}
		}
	}
});

//计算选中值
const computedSelectedData = () => {
	//多选
	if (props.multiple) {
		if (props.fillMap && Object.keys(props.fillMap).length > 0) {
			let tempArray: Array<any> = [];
			Object.keys(props.fillMap).forEach((item: any) => {
				if (props.data && props.data[props.fillMap[item]]) {
					let tempDataArray: Array<any> =
						props.data[props.fillMap[item]].split(',');
					tempDataArray.forEach((tempData: any, index: number) => {
						if (tempArray.length < tempDataArray.length) {
							let singleData: any = { [item]: tempData };
							tempArray.push(singleData);
						} else {
							Object.assign(tempArray[index], { [item]: tempData });
						}
					});
				}
			});
			let tempflag = false;
			if (tempArray && tempArray.length > 0) {
				tempArray.forEach((item: any) => {
					if (!item.label) {
						tempflag = true;
					}
				});
			}
			if (
				tempflag &&
				props.codeListTag &&
				props.codeListType &&
				Object.is(props.codeListType, 'DYNAMIC')
			) {
				let tempStatus = 0;
				tempArray.forEach((item: any) => {
					if (!item.label) {
						tempStatus += 1;
						fillLabel(item, item.id, (result: any) => {
							item = result;
							tempStatus -= 1;
							if (tempStatus === 0) {
								selectTreeValue.value = JSON.stringify(tempArray);
							}
						});
					} else {
						selectTreeValue.value = JSON.stringify(tempArray);
					}
				});
			}
		}
	} else {
		//单选
		if (props.fillMap && Object.keys(props.fillMap).length > 0) {
			let templateValue: any = {};
			Object.keys(props.fillMap).forEach((item: any) => {
				if (props.data && props.data[props.fillMap[item]]) {
					Object.assign(templateValue, {
						[item]: props.data[props.fillMap[item]],
					});
				}
			});
			if (
				!templateValue.label &&
				templateValue.id &&
				props.codeListTag &&
				props.codeListType &&
				Object.is(props.codeListType, 'DYNAMIC')
			) {
				fillLabel(templateValue, templateValue.id, (templateValue: any) => {
					selectTreeValue.value = JSON.stringify([templateValue]);
				});
			} else {
				selectTreeValue.value = JSON.stringify([templateValue]);
			}
		}
	}
};

//填充label
const fillLabel = async (tempObject: any, valueItem: any, callback: any) => {
	if (
		!tempObject.label &&
		tempObject.id &&
		props.codeListTag &&
		props.codeListType &&
		Object.is(props.codeListType, 'DYNAMIC')
	) {
		await App.getAppCodeListHelper()
			.getCodeListItems(props.codeListTag)
			.then((codeListResult: any) => {
				if (codeListResult.ok) {
					const result = codeListResult.data;
					if (result && result.length > 0) {
						let data: any = result.find((item: any) => {
							return Object.is(item.id, valueItem);
						});
						Object.assign(tempObject, { label: data.label });
					}
					callback(tempObject);
				}
			})
			.catch((error: any) => {
				App.getNotificationHelper().error(
					App.ts('common.generic.error'),
					App.ts('common.generic.codenotexist')
				);
			});
	}
};

//初始化数据
const initBasicData = () => {
	if (props.filter) {
		if (props.data && props.data[props.filter]) {
			return props.data[props.filter];
		} else if (props.context && props.context[props.filter]) {
			return props.context[props.filter];
		} else {
			return null;
		}
	}
};

//加载树数据
const loadTreeData = (requestUrl: string) => {
	if (props.filter) {
		const result: any = getOrgData(requestUrl);
		if (result) {
			treeData = result;
			return;
		}
	}
	Http.getHttp()({
		method: props.requestMode,
		url: requestUrl,
		data: {},
	})
		.then((response: any) => {
			if (!response.status || response.status !== 200) {
				console.warn(App.ts('common.generic.loadfail'));
			} else {
				treeData.value = [];
				const result = response.data;
				formatData(result);
				treeData.value = result;
				if (props.filter) {
					addOrgData(requestUrl, result);
				}
			}
		})
		.catch((error: any) => {
			console.warn(error?.message);
		});
};
//选择值
const onChange = (value: any, label: any, extra: any) => {
	emit('component-action', {
		name: `${props.name}`,
		action: 'valueChange',
		data: JSON.stringify(value),
	});
};

//过滤
const filterTreeNode = (inputValue: string, treeNode: any) => {
	const title = treeNode.title || treeNode.label;
	if (title) {
		return title.indexOf(inputValue) < 0 ? false : true;
	}
	return true;
};

//格式化数据
const formatData = (data: any[]) => {
	data.forEach((item: any) => {
		item.value = item.id;
		if (item.children?.length > 0) {
			formatData(item.children);
		}
	});
};
</script>
